import React, { useState, useRef, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TextInput, TouchableOpacity, KeyboardAvoidingView, Platform, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { Colors } from '../constants/colors';
import AppHeader from '../components/AppHeader';
import PersonalInfoModal from '../components/PersonalInfoModal';
import { aiChatService, bodyDataService } from '../services';
import { ChatMessageVo } from '../types/api';
import Markdown from 'react-native-markdown-display';


const quickQuestions = [
  "我該如何開始健身？",
  "如何制定訓練計劃？",
  "減脂期間應該注意什麼？",
  "如何提高肌肉力量？"
];

// 获取指定天数前的时间，格式化为YYYY-MM-DD HH:mm:ss
const getDaysAgoTime = (days: number): string => {
  const date = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 格式化日期显示
const formatDateDisplay = (dateString: string): string => {
  const messageDate = new Date(dateString);

  // 直接返回年月日格式
  const year = messageDate.getFullYear();
  const month = String(messageDate.getMonth() + 1).padStart(2, '0');
  const day = String(messageDate.getDate()).padStart(2, '0');
  return `${year}年${month}月${day}日`;
};

// 检查两个日期是否是同一天
const isSameDay = (date1: string, date2: string): boolean => {
  const d1 = new Date(date1);
  const d2 = new Date(date2);
  return d1.toDateString() === d2.toDateString();
};

export default function AiChatScreen() {
  const navigation = useNavigation<any>();
  const [messages, setMessages] = useState<ChatMessageVo[]>([]);
  const [inputText, setInputText] = useState('');
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [sending, setSending] = useState(false);
  const [currentSessionId, setCurrentSessionId] = useState<number | undefined>();
  const [showPersonalInfoModal, setShowPersonalInfoModal] = useState(false);
  const [hasCheckedPersonalInfo, setHasCheckedPersonalInfo] = useState(false);
  const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
  const [isInitialLoad, setIsInitialLoad] = useState(true);
  const [pageParams, setPageParams] = useState({
    pageNum: 1,
    pageSize: 99999,
    start: getDaysAgoTime(3), // 传入3，获取3天前的时间
    end: getDaysAgoTime(0) // 当前时间，格式化为YYYY-MM-DD
  });
  const flatListRef = useRef<FlatList>(null);

  // 检查个人资料是否完整
  const checkPersonalInfo = async () => {
    if (hasCheckedPersonalInfo) return;

    try {
      const bodyData = await bodyDataService.getBodyData();
      // 检查是否有基本的身體數據
      const hasBasicInfo = bodyData && bodyData.height && bodyData.weight && bodyData.birthday;

      if (!hasBasicInfo) {
        setShowPersonalInfoModal(true);
      }
      setHasCheckedPersonalInfo(true);
    } catch (error: any) {
      // 如果獲取失敗（可能是第一次使用），顯示個人資料設置
      console.log('獲取個人資料失敗，可能是第一次使用:', error);
      setShowPersonalInfoModal(true);
      setHasCheckedPersonalInfo(true);
    }
  };

  // 加載聊天歷史
  const loadChatHistory = async () => {
    try {
      setLoading(true);
      const result = await aiChatService.getHistoryByTimeRange(pageParams);
      const newMessages = result.rows || [];
      console.log(newMessages,'newMessages----------')
      setMessages(newMessages);
      
    } catch (error: any) {
      console.error('加載聊天歷史失敗:', error);
      // 不顯示錯誤提示，因為可能是第一次使用
    } finally {
      setLoading(false);
    }
  };

  // 加载更多历史记录
  const loadMoreHistory = async () => {
    if (loadingMore) return;

    try {
      setLoadingMore(true);
      setShouldAutoScroll(false); // 禁用自动滚动
      setIsInitialLoad(false); // 标记为非初始加载

      // 计算新的时间范围：start为当前start的3天前，end为当前start
      const currentStart = pageParams.start;
      const currentStartDate = new Date(currentStart);
      const newStartDate = new Date(currentStartDate.getTime() - 3 * 24 * 60 * 60 * 1000);

      // 格式化新的开始时间
      const year = newStartDate.getFullYear();
      const month = String(newStartDate.getMonth() + 1).padStart(2, '0');
      const day = String(newStartDate.getDate()).padStart(2, '0');
      const hours = String(newStartDate.getHours()).padStart(2, '0');
      const minutes = String(newStartDate.getMinutes()).padStart(2, '0');
      const seconds = String(newStartDate.getSeconds()).padStart(2, '0');
      const newStart = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      const moreParams = {
        ...pageParams,
        start: newStart,
        end: currentStart
      };

      const result = await aiChatService.getHistoryByTimeRange(moreParams);
      const newMessages = result.rows || [];
      if (newMessages.length > 0) {
        // 将新消息添加到现有消息的前面
        const updatedMessages = [...newMessages, ...messages];
        setMessages(updatedMessages);
        // 更新pageParams的start为新的start
        setPageParams(prev => ({ ...prev, start: newStart }));
      }

    } catch (error: any) {
      console.error('加載更多歷史失敗:', error);
    } finally {
      setLoadingMore(false);
      // 延迟重新启用自动滚动，确保加载完成后的布局变化不会触发滚动
      setTimeout(() => {
        setShouldAutoScroll(true);
      }, 500);
    }
  };

  // 页面聚焦时加载数据
  useFocusEffect(
    React.useCallback(() => {
      setIsInitialLoad(true); // 重置初始加载标志
      loadChatHistory();
      checkPersonalInfo();
    }, [hasCheckedPersonalInfo])
  );

  // 监听messages变化，只在初始加载完成后滚动到底部
  useEffect(() => {
    if (messages.length > 0 && !loading && shouldAutoScroll && isInitialLoad) {
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: false });
        setIsInitialLoad(false); // 滚动后标记初始加载完成
      }, 100);
    }
  }, [messages, loading, shouldAutoScroll, isInitialLoad]);

  const handleSendMessage = async (text?: string) => {
    const messageText = text || inputText.trim();
    if (!messageText || sending) return;

    try {
      setSending(true);
      setInputText('');
      setShouldAutoScroll(true); // 发送消息时启用自动滚动

      // 先显示用户消息
      const userMessage: ChatMessageVo = {
        id: Date.now(),
        userId: 0, // 临时用户ID
        content: messageText,
        role: 'user',
        createTime: new Date().toISOString(),
        sessionId: currentSessionId || 0,
      };

      const updatedMessages = [...messages, userMessage];
      setMessages(updatedMessages);

      // 滚动到底部
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
      }, 100);

      // 发送消息到AI服务
      const response = await aiChatService.sendMessage({
        question: messageText,
        sessionId: currentSessionId,
      });

      console.log('AI聊天响应:', response);

      // 更新会话ID
      if (!currentSessionId) {
        setCurrentSessionId(response.sessionId);
      }

      // 直接显示AI回复，不需要重新查询历史
      if (response && response.answer) {
        console.log('添加AI回复消息:', response.answer);
        const aiMessage: ChatMessageVo = {
          id: Date.now() + 1,
          userId: 0, // AI消息的用户ID
          content: response.answer,
          role: 'assistant',
          createTime: new Date().toISOString(),
          sessionId: response.sessionId || currentSessionId || 0,
        };

        const finalMessages = [...updatedMessages, aiMessage];
        setMessages(finalMessages);

        // 滚动到底部
        setTimeout(() => {
          flatListRef.current?.scrollToEnd({ animated: true });
        }, 100);
      } else {
        console.log('AI响应中没有answer字段:', response);
      }

    } catch (error: any) {
      console.error('发送消息失败:', error);
      Alert.alert('錯誤', error.message || '發送消息失敗，請稍後重試');

      // 恢复输入框内容
      setInputText(messageText);

      // 移除用户消息（如果发送失败）
      const filteredMessages = messages.filter(msg => msg.content !== messageText);
      setMessages(filteredMessages);
    } finally {
      setSending(false);
    }
  };

  const renderMessage = ({ item, index }: { item: ChatMessageVo; index: number }) => {
    const isAiResponse = item.role === 'assistant';

    // 检查是否需要显示日期分隔符
    const shouldShowDateSeparator = () => {
      if (index === 0) return true; // 第一条消息总是显示日期

      const previousMessage = messages[index - 1];
      if (!previousMessage) return true;

      // 比较当前消息和上一条消息的日期
      return !isSameDay(previousMessage.createTime, item.createTime);
    };

    return (
      <View>
        {shouldShowDateSeparator() && (
          <View style={styles.dateSeparatorContainer}>
            <Text style={styles.dateSeparatorText}>
              {formatDateDisplay(item.createTime)}
            </Text>
          </View>
        )}
        <View style={[styles.messageBubble, isAiResponse ? styles.aiMessage : styles.userMessage]}>
          {isAiResponse ? (
            <Markdown style={markdownStyles}>
              {item.content}
            </Markdown>
          ) : (
            <Text style={[styles.messageText, styles.userMessageText]}>
              {item.content}
            </Text>
          )}
          <Text style={[styles.messageTime, isAiResponse ? styles.aiMessageTime : styles.userMessageTime]}>
            {new Date(item.createTime).toLocaleTimeString()}
          </Text>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <AppHeader
        title="AI健康顧問"
        rightAction={{
          icon: 'settings-outline',
          onPress: () => navigation.navigate('ExerciseRecords'),
        }}
      />

      <KeyboardAvoidingView
        style={styles.content}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      >
        {loading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={Colors.primary} />
            <Text style={styles.loadingText}>加載聊天記錄...</Text>
          </View>
        ) : messages.length === 0 ? (
          <View style={styles.welcomeContainer}>
            <View style={styles.aiAvatar}>
              <Ionicons name="chatbubble-ellipses" size={32} color={Colors.primary} />
            </View>
            <Text style={styles.welcomeTitle}>AI健康顧問</Text>
            <Text style={styles.welcomeSubtitle}>我是您的專業健身助手，有什麼問題都可以問我！</Text>

            <View style={styles.quickQuestionsContainer}>
              <Text style={styles.quickQuestionsTitle}>常見問題：</Text>
              {quickQuestions.map((question, index) => (
                <TouchableOpacity
                  key={index}
                  style={[styles.quickQuestionButton, sending && styles.quickQuestionButtonDisabled]}
                  onPress={() => handleSendMessage(question)}
                  disabled={sending}
                >
                  <Text style={styles.quickQuestionText}>{question}</Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
        ) : (
          <View style={{ flex: 1 }}>
            <FlatList
              ref={flatListRef}
              data={messages}
              renderItem={renderMessage}
              keyExtractor={(item) => item.id.toString()}
              style={styles.messagesList}
              contentContainerStyle={styles.messagesContent}
              onContentSizeChange={() => {
                // 只在允许自动滚动时才滚动到底部
                if (shouldAutoScroll) {
                  flatListRef.current?.scrollToEnd({ animated: true });
                }
              }}
              onLayout={() => {
                // 只在允许自动滚动时才滚动到底部
                if (shouldAutoScroll) {
                  flatListRef.current?.scrollToEnd({ animated: true });
                }
              }}
              refreshing={loadingMore}
              onRefresh={loadMoreHistory}
              ListHeaderComponent={
                loadingMore ? (
                  <View style={styles.loadMoreContainer}>
                    <ActivityIndicator size="small" color={Colors.primary} />
                    <Text style={styles.loadMoreText}>加載更多歷史記錄...</Text>
                  </View>
                ) : null
              }
            />
            {sending && (
              <View style={styles.sendingIndicator}>
                <ActivityIndicator size="small" color={Colors.primary} />
                <Text style={styles.sendingText}>分析中...</Text>
              </View>
            )}
          </View>
        )}

        <View style={styles.inputContainer}>
          <TextInput
            style={styles.textInput}
            placeholder="輸入您的問題..."
            placeholderTextColor={Colors.gray[500]} // 修复placeholder颜色问题
            value={inputText}
            onChangeText={setInputText}
            multiline
            maxLength={500}
          />
          <TouchableOpacity
            style={[styles.sendButton, (!inputText.trim() || sending) && styles.sendButtonDisabled]}
            onPress={() => handleSendMessage()}
            disabled={!inputText.trim() || sending}
          >
            {sending ? (
              <ActivityIndicator size={20} color={Colors.white} />
            ) : (
              <Ionicons name="send" size={20} color={Colors.white} />
            )}
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>

      <PersonalInfoModal
        visible={showPersonalInfoModal}
        onClose={() => setShowPersonalInfoModal(false)}
        onComplete={() => setHasCheckedPersonalInfo(true)}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  content: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: Colors.gray[600],
  },
  welcomeContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 32,
  },
  aiAvatar: {
    width: 80,
    height: 80,
    backgroundColor: Colors.gray[100],
    borderRadius: 40,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 16,
  },
  welcomeTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: Colors.gray[800],
    marginBottom: 8,
  },
  welcomeSubtitle: {
    fontSize: 16,
    color: Colors.gray[600],
    textAlign: 'center',
    lineHeight: 24,
    marginBottom: 32,
  },
  quickQuestionsContainer: {
    width: '100%',
  },
  quickQuestionsTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: Colors.gray[700],
    marginBottom: 16,
  },
  quickQuestionButton: {
    backgroundColor: Colors.gray[100],
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 20,
    marginBottom: 8,
  },
  quickQuestionButtonDisabled: {
    opacity: 0.6,
  },
  quickQuestionText: {
    fontSize: 14,
    color: Colors.gray[700],
  },
  messagesList: {
    flex: 1,
  },
  messagesContent: {
    padding: 16,
  },
  // 日期分隔符样式
  dateSeparatorContainer: {
    alignItems: 'center',
    marginVertical: 16,
  },
  dateSeparatorText: {
    fontSize: 14,
    color: Colors.gray[500],
    fontWeight: '500',
    backgroundColor: Colors.gray[50],
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 12,
    overflow: 'hidden',
  },
  messageBubble: {
    maxWidth: '80%',
    marginVertical: 4,
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 18,
  },
  userMessage: {
    alignSelf: 'flex-end',
    backgroundColor: Colors.primary,
  },
  aiMessage: {
    alignSelf: 'flex-start',
    backgroundColor: Colors.gray[100],
  },
  messageText: {
    fontSize: 16,
    lineHeight: 22,
  },
  userMessageText: {
    color: Colors.white,
  },
  aiMessageText: {
    color: Colors.gray[800],
  },
  messageTime: {
    fontSize: 12,
    marginTop: 4,
  },
  userMessageTime: {
    color: Colors.white + 'CC',
    textAlign: 'right',
  },
  aiMessageTime: {
    color: Colors.gray[500],
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: Colors.white,
    borderTopWidth: 1,
    borderTopColor: Colors.gray[200],
  },
  textInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: Colors.gray[300],
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 12, // 增加垂直padding确保文本居中
    fontSize: 16,
    minHeight: 40, // 确保安卓上有足够的高度
    maxHeight: 100,
    marginRight: 8,
    textAlignVertical: 'center', // 改为居中对齐
    includeFontPadding: false, // 安卓特有属性，减少字体内边距
  },
  sendButton: {
    width: 40,
    height: 40,
    backgroundColor: Colors.primary,
    borderRadius: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  sendButtonDisabled: {
    backgroundColor: Colors.gray[300],
  },
  sendingIndicator: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 12,
    backgroundColor: Colors.gray[100],
  },
  sendingText: {
    marginLeft: 8,
    fontSize: 14,
    color: Colors.gray[600],
  },
  sendingSubText: {
    marginLeft: 8,
    fontSize: 12,
    color: Colors.gray[500],
    marginTop: 2,
  },
  loadMoreContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 16,
  },
  loadMoreText: {
    marginLeft: 8,
    fontSize: 14,
    color: Colors.gray[600],
  },
});

// Markdown样式
const markdownStyles = {
  body: {
    fontSize: 16,
    color: Colors.gray[800],
    lineHeight: 24,
  },
  paragraph: {
    marginBottom: 8,
  },
  strong: {
    fontWeight: '700' as const,
  },
  em: {
    fontStyle: 'italic' as const,
  },
  code_inline: {
    backgroundColor: Colors.gray[100],
    paddingHorizontal: 4,
    paddingVertical: 2,
    borderRadius: 4,
    fontSize: 14,
    fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace',
  },
  code_block: {
    backgroundColor: Colors.gray[100],
    padding: 12,
    borderRadius: 8,
    marginVertical: 8,
    fontSize: 14,
    fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace',
  },
  bullet_list: {
    marginBottom: 8,
  },
  ordered_list: {
    marginBottom: 8,
  },
  list_item: {
    marginBottom: 4,
  },
};
